Enums

  • Syntax:

    • In C and C++:

      enum type_name {
          value1,
          value2,
          value3,
          .
          .
      } variables_with_this_type;
      
    • In C++11 and forward:

      enum class type_name {
          value1,
          value2,
          value3,
          .
          .
      } variables_with_this_type;
      
      • or

      enum struct type_name {
          value1,
          value2,
          value3,
          .
          .
      } variables_with_this_type;
      
      • "To create real enum types that are neither implicitly convertible to int and that neither have enumerator values of type int, but of the enum type itself, thus preserving type safety."

      • The choice between class and struct here is purely syntactic; unlike normal class/struct types, there is no difference in default access or behavior.

  • Examples:

    enum Color { Red, Green, Blue };  // implicitly convert to int.
    enum class  Color : uint8_t { Red, Green, Blue }; // doesn't not implicit convert to int.
    enum struct Color : uint8_t { Red, Green, Blue }; // doesn't not implicit convert to int.